<template>
  <el-dialog
    :title="'绑定收费项'"
    v-model="model"
    width="600px"
    :before-close="closeHandle"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="收费项" prop="feeId">
        <el-select v-model="form.feeId" placeholder="请选择">
          <el-option
            v-for="item in feeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeHandle">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup name="bindResident">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  getChargingStandardPage,
  batchUpdateFeeConfigToBuildingRoom,
} from "@/api/realEstateManage";

const props = defineProps({
  ids: {
    type: Array,
    default: () => [],
  },
  row: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["submit"]);
const model = defineModel({
  default: false,
});

const formRef = ref();
const form = ref({
  ids: [],
});

const rules = reactive({
  feeId: [{ required: true, message: "请选择收费项" }],
});

onMounted(() => {
  if (props.ids.length) {
    form.value.ids = props.ids;
  }
});

const feeList = ref([]);
const getFeeList = () => {
  getChargingStandardPage({
    pageNo: 1,
    pageSize: 999,
    communityId: props.row.communityId,
  }).then(({ data }) => {
    const result = data.records.map((item) => ({
      value: item.id,
      label: item.communityName + " - " + item.name,
    }));
    feeList.value = result;
  });
};
getFeeList();

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      batchUpdateFeeConfigToBuildingRoom({
        type: 0,
        communityId: props.row.communityId,
        roomIds: props.ids,
        communityFeeConfigId: form.value.feeId,
      }).then(({ data }) => {
        if (data) {
          ElMessage({
            message: "绑定成功",
            type: "success",
          });
          closeHandle();
          emit("submit");
        }
      });
    }
  });
};

const closeHandle = () => {
  model.value = false;
};
</script>

<style scoped>
.el-cascader {
  width: 100%;
}
</style>
